package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.constant.BompAppParamConstant;
import cc.rengu.igas.bomp.common.constant.BompTreeNodeConstant;
import cc.rengu.igas.bomp.common.constant.TableNameConstant;
import cc.rengu.igas.bomp.common.dao.*;
import cc.rengu.igas.bomp.common.dao.impl.*;
import cc.rengu.igas.bomp.common.entity.*;
import cc.rengu.igas.bomp.common.enums.*;
import cc.rengu.igas.bomp.common.util.ChangeNextStatusUtil;
import cc.rengu.igas.bomp.common.util.CompareFieldsUtil;
import cc.rengu.igas.bomp.common.util.InitParamUtil;
import cc.rengu.igas.bomp.core.model.UserSessionInfo;
import cc.rengu.igas.bomp.core.realize.MchntVerifyService;
import cc.rengu.igas.bomp.core.realize.impl.MchntVerifyServiceImpl;
import cc.rengu.igas.bomp.core.service.base.AuditService;
import cc.rengu.igas.bomp.facade.bean.MchntApexInfoBean;
import cc.rengu.igas.bomp.facade.bean.MchntBaseInfoBean;
import cc.rengu.igas.bomp.facade.bean.MchntContactsInfoBean;
import cc.rengu.igas.bomp.facade.enums.BompManageOprTypeEnum;
import cc.rengu.igas.bomp.facade.enums.BompMchntAttributeEnum;
import cc.rengu.igas.bomp.facade.enums.BompMchntStatusEnum;
import cc.rengu.igas.bomp.facade.enums.BompMchntTypeEnum;
import cc.rengu.igas.bomp.facade.request.MchntBaseInfoManageRequest;
import cc.rengu.igas.bomp.facade.response.MchntBaseInfoManageResponse;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * 商户基本信息管理
 *
 * @author: zhangxuran
 * @Date: 2020/3/29 15:57
 * @Description: 商户基本信息管理
 */
public class MchntBaseInfoManageService extends AuditService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        MchntBaseInfoManageRequest request = new MchntBaseInfoManageRequest();
        ConvertUtil.convertOutput(request);

        if (!BompManageOprTypeEnum.isBompManageOprTypeByType(request.getOprType())) {
            rglog.error("商户基本信息管理失败！操作类型不符合规定！传入instId:{},前端流水号:{}，oprType:{}."
                    , request.getHeader().getInstId(), request.getHeader().getTraceNo(), request.getOprType());
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(),
                    RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        MchntBaseInfoBean mchntBaseInfoBean = request.getMchntBaseInfoBean();
        //审核时参数校验
        if (StringUtil.isEmptyOrNull(mchntBaseInfoBean.getIndustryType())
                || StringUtil.isEmptyOrNull(mchntBaseInfoBean.getManagementScope())) {
            rglog.error("商户基本信息管理失败！行业类型，经营范围必填！传入instId:{},前端流水号:{}."
                    , request.getHeader().getInstId(), request.getHeader().getTraceNo());
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        //商户等级为小微商户时，必须录入负责人证件信息
        if (BompMchntTypeEnum.WECHAT_MCHNT.getMchntType().equals(mchntBaseInfoBean.getMchntType())
                && null == request.getMchntContactsInfoBean()) {
            rglog.error("商户等级为小微商户时，必须录入负责人证件信息！拒绝新增商户信息！instId:{},前端流水号:{}",
                    request.getHeader().getInstId(), request.getHeader().getTraceNo());
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        //线上收银台的产品，“网络域名”、“ICP备案/许可证号”、登记IP必填
        if (!BompMchntAttributeEnum.verifyBompMchntAttributeEnumByType(mchntBaseInfoBean.getMchntAttr())) {
            rglog.error("商户属性不符合枚举值！instId:{},前端流水号:{},mchntAttr:{}",
                    request.getHeader().getInstId(), request.getHeader().getTraceNo(), mchntBaseInfoBean.getMchntAttr());
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        if (BompMchntAttributeEnum.ONLINE.getType().equals(mchntBaseInfoBean.getMchntAttr())
                || BompMchntAttributeEnum.ONLINE_WITH_OFFLINE.getType().equals(mchntBaseInfoBean.getMchntAttr())) {
            if (StringUtil.isEmptyOrNull(mchntBaseInfoBean.getIp())
                    || StringUtil.isEmptyOrNull(mchntBaseInfoBean.getMchntNetworkDomain())
                    || StringUtil.isEmptyOrNull(mchntBaseInfoBean.getIcpRecordNo())) {
                rglog.error("商户属性不符合枚举值！instId:{},前端流水号:{},mchntAttr:{}",
                        request.getHeader().getInstId(), request.getHeader().getTraceNo(), mchntBaseInfoBean.getMchntAttr());
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            }
        }

        return request;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        MchntBaseInfoManageRequest mchntBaseInfoManageRequest = (MchntBaseInfoManageRequest) request;
        BizResponse<MchntBaseInfoManageResponse> bizResponse = new BizResponse<>();
        MchntBaseInfoManageResponse mchntBaseInfoManageResponse = new MchntBaseInfoManageResponse();

        MchntContactsInfoBean mchntContactsInfoBean = mchntBaseInfoManageRequest.getMchntContactsInfoBean();
//        if (!"MCMP".equals(mchntBaseInfoManageRequest.getHeader().getChanlId())) {
//            String sessionObjStr = RedisUtil.onceGet(mchntBaseInfoManageRequest.getHeader().getSession());
//            UserSessionInfo userSessionInfo = JSON.parseObject(sessionObjStr, UserSessionInfo.class);
//            //解密敏感信息
//            if (!StringUtil.isEmptyOrNull(mchntContactsInfoBean.getContactMobile())) {
//                mchntContactsInfoBean.setContactMobile(descriptData(userSessionInfo.getSensitiveKey(), mchntContactsInfoBean.getContactMobile()));
//            }
//
//            if (!StringUtil.isEmptyOrNull(mchntContactsInfoBean.getContactPhone())) {
//                mchntContactsInfoBean.setContactPhone(descriptData(userSessionInfo.getSensitiveKey(), mchntContactsInfoBean.getContactPhone()));
//            }
//
//            if (!StringUtil.isEmptyOrNull(mchntContactsInfoBean.getContactCertNo())) {
//                mchntContactsInfoBean.setContactCertNo(descriptData(userSessionInfo.getSensitiveKey(), mchntContactsInfoBean.getContactCertNo()));
//            }
//
//            mchntBaseInfoManageRequest.setMchntContactsInfoBean(mchntContactsInfoBean);
//        }

        if (BompManageOprTypeEnum.CREATE.getType().equals(mchntBaseInfoManageRequest.getOprType())) {

            //新增商户基本信息
            String mchntNo = increaseMchntBaseInfo(mchntBaseInfoManageRequest);
            mchntBaseInfoManageResponse.setMchntNo(mchntNo);

        } else if (BompManageOprTypeEnum.MODIFY.getType().equals(mchntBaseInfoManageRequest.getOprType())) {
            //修改商户基本信息
            String mchntNo = modifyMchntBaseInfo(mchntBaseInfoManageRequest);
            mchntBaseInfoManageResponse.setMchntNo(mchntNo);
        } else {
            //审核商户基本信息
            rglog.error("不允许单个页面进行审核操作！instId:{},前端流水号:{}",
                    mchntBaseInfoManageRequest.getHeader().getInstId(), mchntBaseInfoManageRequest.getHeader().getTraceNo());
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        mchntBaseInfoManageResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        mchntBaseInfoManageResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(mchntBaseInfoManageResponse);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        return bizResponse;
    }

    /**
     * 修改商户基本信息
     *
     * @param request 请求
     * @throws Exception 异常
     */
    private String modifyMchntBaseInfo(MchntBaseInfoManageRequest request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        MchntBaseInfoBean mchntBaseInfoBean = request.getMchntBaseInfoBean();
        String instId = request.getHeader().getInstId();
        MchntContactsInfoBean mchntContactsInfoBean = request.getMchntContactsInfoBean();
        List<MchntApexInfoBean> mchntApexInfoBeanList = request.getMchntApexInfoBeanList();
        MchntBaseInfoMapper mchntBaseInfoMapper = new MchntBaseInfoMapperImpl();
        MchntBaseInfo dbMchntBaseInfo = (MchntBaseInfo) xmlTreeUtil.getXmlTreeObjectValue(BompTreeNodeConstant.MCHNT_BASE_INFO, MchntBaseInfo.class);
        if (null == dbMchntBaseInfo) {
            dbMchntBaseInfo = mchntBaseInfoMapper.selectMchntBaseInfoByPrimaryKey(instId, mchntBaseInfoBean.getMchntNo());

            if (null == dbMchntBaseInfo) {
                rglog.error("修改商户信息失败, 根据商户号查询商户信息为空，instId:{},mchntNo:{}",
                        instId, mchntBaseInfoBean.getMchntNo());
                throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
            }
        }

        //判断当前状态是否允许修改
        if (!ChangeNextStatusUtil.isAllowModifyData(dbMchntBaseInfo.getAuditStatus())) {
            rglog.error("修改商户信息失败, 当前商户审核状态不允许修改，instId:{},mchntNo:{},当前商户审核状态:{}",
                    instId, mchntBaseInfoBean.getMchntNo(), dbMchntBaseInfo.getAuditStatus());
            throw new BizException(RespCodeEnum.MANAGE_OPERATE_ERROR.getRespCode(), RespCodeEnum.MANAGE_OPERATE_ERROR.getRespDesc());
        }

        //默认修改待审核
        String auditStatus = AuditStatusEnum.MODIFY_BE_COMMIT_AUDIT.getAuditStatus();
        //modifyMchntBaseInfo 修改的数据
        MchntBaseInfo modifyMchntBaseInfo = InitParamUtil.initMchntBaseInfoByModify(mchntBaseInfoBean,
                mchntContactsInfoBean, dbMchntBaseInfo, request.getUserId(), auditStatus);
        //默认临时表操作类型为修改
        String bizTmpBizOpr = "U";
        if (AuditStatusEnum.BE_AUDIT.getAuditStatus().equals(dbMchntBaseInfo.getAuditStatus())
                || AuditStatusEnum.ADD_AUDIT_REJECT.getAuditStatus().equals(dbMchntBaseInfo.getAuditStatus())) {
            /* 黑名单校验 */
            MchntVerifyService mchntVerifyService = new MchntVerifyServiceImpl();
            if (mchntVerifyService.checkMchntBlackInfoByMchntNetworkDomain(mchntBaseInfoBean.getMchntNetworkDomain())) {
                rglog.error("商户基本信息管理-修改商户失败！黑名单校验失败！instId:{},signInstId:{},networkDomain:{}."
                        , instId, mchntBaseInfoBean.getSignInstId(), mchntBaseInfoBean.getMchntNetworkDomain());
                throw new BizException(RespCodeEnum.BLACK_LIST_NET_WORD.getRespCode(), RespCodeEnum.BLACK_LIST_NET_WORD.getRespDesc());
            }
            //新增草稿状态修改或新增审核失败修改 -> 提交待审核
            rglog.debug("新增草稿状态修改或新增审核失败修改");
            auditStatus = AuditStatusEnum.BE_AUDIT.getAuditStatus();
            bizTmpBizOpr = "I";
            dbMchntBaseInfo = InitParamUtil.initMchntBaseInfoByCreateModify(request, mchntBaseInfoBean,
                    mchntContactsInfoBean, dbMchntBaseInfo);
            modifyMchntBaseInfo = dbMchntBaseInfo;
        } else if (!BompMchntStatusEnum.NORMAL.getType().equals(dbMchntBaseInfo.getMchntStatus())) {
            //正式商户才允许进行修改  （商户状态修改由商户状态管理交易进行处理）
            rglog.error("修改商户信息失败, 根据商户号查询商户状态非正式商户不允许进行修改，instId:{},mchntNo:{}",
                    instId, mchntBaseInfoBean.getMchntNo());
            throw new BizException(RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespCode(), RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespDesc());
        }


        //需要审核，更新正式表的信息为修改待审核，将传入的商户信息更新到业务临时表
        //原商户信息修改审核状态
        dbMchntBaseInfo.setAuditStatus(auditStatus);
        dbMchntBaseInfo.setLastOprId(request.getUserId());
        dbMchntBaseInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));

        //不允许修改的数据
        //商户名称、商户类型、商户性质、经营类目、联系人信息、营业执照信息、法人信息应该都不能修改。
        //商户状态，是否开通本行卡实时清算，商户结算模式，提现标识 在其他接口进行修改，此处不允许修改
        String[] errorArr = new String[]{"mchntName", "mchntAttr", "mchntNature",
                "managementScope", "industryType",
                "realSettleFlag", "mchntSettleMode",
                "mchntDelayFlag", "cashWithdrawalFlag",
                "mchntStatus"};
        String compareModifyError = CompareFieldsUtil.noAllowModifyFields(dbMchntBaseInfo, modifyMchntBaseInfo, errorArr);
        if (!StringUtil.isEmptyOrNull(compareModifyError)) {
            rglog.error("商户基本信息管理-修改商户商户基本信息，修改了不允许修改的数据！");
        }

        BizTmp bizTmp = new BizTmp();
        BizTmpMapper bizTmpMapper = new BizTmpMapperImpl();
        //先查在更新，无则插入数据  （场景：之前是无需检查，现在需要检查）
        BizTmp oldBizTemp = bizTmpMapper.selectBizTmpByRealId(dbMchntBaseInfo.getInstId(), dbMchntBaseInfo.getId());
        if (null == oldBizTemp) {
            rglog.error("修改商户基本信息失败！业务临时表数据为空{}", dbMchntBaseInfo.getId());
            ConvertUtil.convertOutput(bizTmp);
            BeanUtil.beanCopy(dbMchntBaseInfo, bizTmp);
            BeanUtil.beanCopy(modifyMchntBaseInfo, bizTmp);
            bizTmp.setManageInstId(dbMchntBaseInfo.getSignInstId());
            bizTmp.setRealId(dbMchntBaseInfo.getId());
            bizTmp.setDetailFlag(BompAppParamConstant.FLAG_N);
        } else {
            BeanUtil.beanCopy(oldBizTemp, bizTmp);
            ConvertUtil.convertOutput(bizTmp);
            BeanUtil.beanCopy(modifyMchntBaseInfo, bizTmp);
        }
        bizTmp.setBizStatus(BizTmpStatusEnum.NO_NORMAL.getType());
        //修改
        bizTmp.setBizOpr(bizTmpBizOpr);
        //修改待审批
        bizTmp.setAuditStatus(auditStatus);
        bizTmp.setMasterShowFlag(request.getMasterShowFlag());
        bizTmp.setOprTableEname(TableNameConstant.T_B_MCHNT_BASE_INFO);
        //将待修改的商户信息存入 bizTmp
        String modifyMchntBaseInfoJson = JSONObject.toJSONString(modifyMchntBaseInfo);
        InitParamUtil.initBizTempData(bizTmp, modifyMchntBaseInfoJson);

        modifyMchntBaseInfoData(xmlTreeUtil, dbMchntBaseInfo, mchntBaseInfoMapper, bizTmp, null, mchntApexInfoBeanList);
        return mchntBaseInfoBean.getMchntNo();

    }


    private void modifyMchntBaseInfoData(XmlTreeUtil xmlTreeUtil,
                                         MchntBaseInfo mchntBaseInfo,
                                         MchntBaseInfoMapper mchntBaseInfoMapper,
                                         BizTmp bizTmp,
                                         BizHistory bizHistory,
                                         List<MchntApexInfoBean> mchntApexInfoBeanList) throws Exception {
        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MCMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MCMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        try {
            int dbResult = mchntBaseInfoMapper.updateMchntBaseInfoById(mchntBaseInfo);
            if (dbResult != 0) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("修改商户基本信息表失败！id:{},mchnt:{},instId:{}",
                        mchntBaseInfo.getId(), mchntBaseInfo.getMchntNo(), mchntBaseInfo.getInstId());
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }

            if (null != bizTmp) {
                BizTmpMapper bizTmpMapper = new BizTmpMapperImpl();
                //先查在更新，无则插入数据  （场景：之前是无需检查，现在需要检查）
                dbResult = bizTmpMapper.insertBizTmp(bizTmp);
                if (dbResult != 0) {
                    dbResult = bizTmpMapper.updateBizTmpByRealId(bizTmp);
                    if (dbResult != 0) {
                        dbsUtil.dbsEndTransaction(false);
                        rglog.error("修改商户基本信息-登记/更新临时表记录失败！realId:{},manageInstId:{},instId:{}",
                                bizTmp.getRealId(), bizTmp.getManageInstId(), bizTmp.getInstId());
                        throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                    }
                }
            }

            if (null != bizHistory) {
                BizHistoryMapper bizHistoryMapper = new BizHistoryMapperImpl();
                dbResult = bizHistoryMapper.insertBompBizHistory(bizHistory);
                if (dbResult != 0) {
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("修改商户基本信息-业务历史表记录失败！realId:{},manageInstId:{},instId:{}",
                            bizHistory.getRealId(), bizHistory.getManageInstId(), bizHistory.getInstId());
                    throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                }
            }

            if (null != mchntApexInfoBeanList && !mchntApexInfoBeanList.isEmpty()) {
                MchntApexInfoMapper mchntApexInfoMapper = new MchntApexInfoMapperImpl();
                for (MchntApexInfoBean mchntApexInfoBean : mchntApexInfoBeanList) {
                    MchntApexInfo mchntApexInfo = new MchntApexInfo();
                    BeanUtil.beanCopy(mchntApexInfoBean, mchntApexInfo);
                    if (StringUtil.isEmptyOrNull(mchntApexInfo.getEffectiveDate())) {
                        mchntApexInfo.setEffectiveDate(DateUtil.getCurrentDate());
                    }
                    if (StringUtil.isEmptyOrNull(mchntApexInfo.getExpiryDate())) {
                        mchntApexInfo.setExpiryDate(BompAppParamConstant.DEFAULT_EXPIRY_DATE);
                    }
                    if (StringUtil.isEmptyOrNull(mchntApexInfo.getPropertyStatus())) {
                        mchntApexInfo.setPropertyStatus(AppParamConstant.YES);
                    }
                    mchntApexInfo.setInstId(mchntBaseInfo.getInstId());
                    mchntApexInfo.setMchntNo(mchntBaseInfo.getMchntNo());
                    mchntApexInfo.setId(RandomUtil.getUUID());
                    mchntApexInfo.setOprId(mchntBaseInfo.getOprId());
                    mchntApexInfo.setCreateTime(mchntBaseInfo.getCreateTime());
                    dbResult = mchntApexInfoMapper.updateMchntApexInfoByPrimaryKey(mchntApexInfo);
                    if (dbResult != 0) {
                        if (1403 == dbResult) {
                            dbResult = mchntApexInfoMapper.insertMchntApexInfo(mchntApexInfo);
                            if (dbResult != 0) {
                                dbsUtil.dbsEndTransaction(false);
                                rglog.error("新增商户扩展属性信息记录失败！");
                                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(),
                                        RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                            }
                        } else {
                            dbsUtil.dbsEndTransaction(false);
                            rglog.error("更新商户扩展属性信息记录失败！");
                            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(),
                                    RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                        }
                    }
                }
            }

            dbsUtil.dbsEndTransaction(true);
        } catch (Exception e) {
            dbsUtil.dbsEndTransaction(false);
            rglog.error("商户基本信息管理失败！mchntNo:{}", mchntBaseInfo.getMchntNo());
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }


    /**
     * 新增商户基本信息
     *
     * @param request 请求
     * @throws Exception 异常
     */
    private String increaseMchntBaseInfo(MchntBaseInfoManageRequest request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String instId = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID);
        MchntBaseInfoBean mchntBaseInfoBean = request.getMchntBaseInfoBean();
        MchntContactsInfoBean mchntContactsInfoBean = request.getMchntContactsInfoBean();
        List<MchntApexInfoBean> mchntApexInfoBeanList = request.getMchntApexInfoBeanList();

        //校验录入的客户经理工号，判断客户经理是否存在
        ManagerInfoMapper managerInfoMapper = new ManagerInfoMapperImpl();
        List<ManagerInfo> managerInfoList = managerInfoMapper.selectBompManagerInfoByManagerId(request.getHeader().getInstId(), mchntBaseInfoBean.getManagerId());
        if (CollectionUtils.isEmpty(managerInfoList)) {
            rglog.error("查询拓展经理信息为空！商户基本信息管理-新增商户失败！instId:{},signInstId:{},managerId:{}."
                    , instId, mchntBaseInfoBean.getSignInstId(), mchntBaseInfoBean.getManagerId());
            throw new BizException(RespCodeEnum.MANAGE_OPERATE_ERROR.getRespCode(), RespCodeEnum.MANAGE_OPERATE_ERROR.getRespDesc());
        }

        ManagerInfo managerInfo = managerInfoList.get(0);
        if (MchntTypeEnum.CHAIN_MCHNT_STORE.getMchntType().equals(mchntBaseInfoBean.getMchntType())) {
            //若为连锁商户门店，则不校验签约机构与拓展经理的关系
            managerInfo = managerInfoList.get(0);
        } else if (StringUtil.isEmptyOrNull(mchntBaseInfoBean.getAgentMchntNo())) {
            managerInfo = managerInfoMapper.selectManagerInfoByPrimaryKey(
                    instId, mchntBaseInfoBean.getSignInstId(), mchntBaseInfoBean.getManagerId());
        } else {
            managerInfo = managerInfoMapper.selectManagerInfoByPrimaryKey(
                    instId, mchntBaseInfoBean.getAgentMchntNo(), mchntBaseInfoBean.getManagerId());
        }

        if (null == managerInfo) {
            rglog.error("查询拓展经理信息为空！商户基本信息管理-新增商户失败！instId:{},signInstId:{},managerId:{}."
                    , instId, mchntBaseInfoBean.getSignInstId(), mchntBaseInfoBean.getManagerId());
            throw new BizException(RespCodeEnum.MANAGE_OPERATE_ERROR.getRespCode(), RespCodeEnum.MANAGE_OPERATE_ERROR.getRespDesc());
        }

        if ((!StringUtil.isEmptyOrNull(mchntContactsInfoBean.getContactMobile()) && mchntContactsInfoBean.getContactMobile().equals(managerInfo.getManagerPhone()))
                || (!StringUtil.isEmptyOrNull(mchntContactsInfoBean.getContactPhone()) && mchntContactsInfoBean.getContactPhone().equals(managerInfo.getManagerPhone()))) {
            rglog.error("拓展经理电话与商户联系人电话一样！不允许进行商户入驻！instId:{},ContactMobile:{},ContactPhone:{},ManagerPhone:{}."
                    , instId, mchntContactsInfoBean.getContactMobile(), mchntContactsInfoBean.getContactPhone(), managerInfo.getManagerPhone());
            throw new BizException(RespCodeEnum.MCHNT_MANAGE_PHONE_MATCH.getRespCode(), RespCodeEnum.MCHNT_MANAGE_PHONE_MATCH.getRespDesc());
        }

        if (MchntTypeEnum.CHAIN_MCHNT_STORE.getMchntType().equals(mchntBaseInfoBean.getMchntType())) {
            if (StringUtil.isEmptyOrNull(mchntBaseInfoBean.getChainMchntNo())) {
                rglog.error("新增门店 连锁商户号必填！instId:{},ChainMchntNo:{}."
                        , instId, mchntBaseInfoBean.getChainMchntNo());
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            }

            if (!(BompAppParamConstant.FLAG_N.equals(mchntBaseInfoBean.getIndependentDataFlag())
                    || BompAppParamConstant.FLAG_Y.equals(mchntBaseInfoBean.getIndependentDataFlag()))) {
                rglog.error("新增门店是否独立维护字段必填！instId:{},ChainMchntNo:{},IndependentDataFlag:{}."
                        , instId, mchntBaseInfoBean.getChainMchntNo(), mchntBaseInfoBean.getIndependentDataFlag());
                throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
            }

            MchntBaseInfoMapper mchntBaseInfoMapper = new MchntBaseInfoMapperImpl();
            MchntBaseInfo chainMchntInfo = mchntBaseInfoMapper.selectMchntBaseInfoByPrimaryKey(instId, mchntBaseInfoBean.getChainMchntNo());
            if (null == chainMchntInfo) {
                rglog.error("新增门店 连锁商户不存在！instId:{},ChainMchntNo:{}."
                        , instId, mchntBaseInfoBean.getChainMchntNo());
                throw new BizException(RespCodeEnum.CHAIN_IS_NULL.getRespCode(), RespCodeEnum.CHAIN_IS_NULL.getRespDesc());
            }

            if (!MchntStatusEnum.NORMAL.getStatus().equals(chainMchntInfo.getMchntStatus())) {
                rglog.error("新增门店 连锁商户状态非正式不允许进行该操作！instId:{},ChainMchntNo:{}."
                        , instId, mchntBaseInfoBean.getChainMchntNo());
                throw new BizException(RespCodeEnum.CHAIN_IS_NOT_NORMAL.getRespCode(), RespCodeEnum.CHAIN_IS_NOT_NORMAL.getRespDesc());
            }
        }


        OrganizationMapper organizationMapper = new OrganizationMapperImpl();
        Organization organization = organizationMapper.selectOrganizationByPrimaryKey(instId, mchntBaseInfoBean.getSignInstId());
        if (null == organization) {
            rglog.error("查询机构信息为空！商户基本信息管理-新增商户失败！instId:{},signInstId:{},managerId:{}."
                    , instId, mchntBaseInfoBean.getSignInstId(), mchntBaseInfoBean.getManagerId());
            throw new BizException(RespCodeEnum.SIGN_INST_IS_NULL.getRespCode(), RespCodeEnum.SIGN_INST_IS_NULL.getRespDesc());
        }

        if (!StringUtil.isEmptyOrNull(mchntBaseInfoBean.getPlatMchntNo())) {
            PlatMchntInfoMapper platMchntInfoMapper = new PlatMchntInfoMapperImpl();
            PlatMchntInfo platMchntInfo = platMchntInfoMapper.selectPlatMchntInfoByMchntNo(instId, mchntBaseInfoBean.getPlatMchntNo());

            if (null == platMchntInfo) {
                rglog.error("查询平台信息为空！商户基本信息管理-新增商户失败！instId:{},PlatMchntNo:{},managerId:{}."
                        , instId, mchntBaseInfoBean.getSignInstId(), mchntBaseInfoBean.getPlatMchntNo());
                throw new BizException(RespCodeEnum.PLAT_INST_IS_NULL.getRespCode(), RespCodeEnum.PLAT_INST_IS_NULL.getRespDesc());
            }

        }

        if (!StringUtil.isEmptyOrNull(mchntBaseInfoBean.getAgentMchntNo())) {
            AgentInfoMapper agentInfoMapper = new AgentInfoMapperImpl();
            AgentInfo agentInfo = agentInfoMapper.selectAgentInfoByPrimaryKey(instId, mchntBaseInfoBean.getAgentMchntNo());
            if (null == agentInfo) {
                rglog.error("查询代理信息为空！商户基本信息管理-新增商户失败！instId:{},AgentMchntNo:{},managerId:{}."
                        , instId, mchntBaseInfoBean.getSignInstId(), mchntBaseInfoBean.getAgentMchntNo());
                throw new BizException(RespCodeEnum.AGENT_INST_IS_NULL.getRespCode(), RespCodeEnum.AGENT_INST_IS_NULL.getRespDesc());
            }
        }

        if (!StringUtil.isEmptyOrNull(mchntBaseInfoBean.getGroupMchntNo())) {
            GroupMchntInfoMapper groupMchntInfoMapper = new GroupMchntInfoMapperImpl();
            GroupMchntInfo groupMchntInfo = groupMchntInfoMapper.selectGroupMchntInfoByPrimaryKey(instId, mchntBaseInfoBean.getGroupMchntNo());
            if (null == groupMchntInfo) {
                rglog.error("查询集团信息为空！商户基本信息管理-新增商户失败！instId:{},GroupMchntNo:{},managerId:{}."
                        , instId, mchntBaseInfoBean.getSignInstId(), mchntBaseInfoBean.getGroupMchntNo());
                throw new BizException(RespCodeEnum.GROUP_INST_IS_NULL.getRespCode(), RespCodeEnum.GROUP_INST_IS_NULL.getRespDesc());
            }
        }


        /* 黑名单校验 */
        MchntVerifyService mchntVerifyService = new MchntVerifyServiceImpl();
        if (mchntVerifyService.checkMchntBlackInfoByMchntNetworkDomain(mchntBaseInfoBean.getMchntNetworkDomain())) {
            rglog.error("商户基本信息管理-新增商户失败！黑名单校验失败！instId:{},signInstId:{},networkDomain:{}."
                    , instId, mchntBaseInfoBean.getSignInstId(), mchntBaseInfoBean.getMchntNetworkDomain());
            throw new BizException(RespCodeEnum.BLACK_LIST_NET_WORD.getRespCode(), RespCodeEnum.BLACK_LIST_NET_WORD.getRespDesc());
        }

        //生成商户号 3位法人行号 + yyMM + 4位行业类型 + 4位序号
        BompSequenceMapper bompSequenceMapper = new BompSequenceMapperImpl();
        //4位序号
        String mchntNoSuffix = bompSequenceMapper.getNextMchntNoSeq();
        String mchntNo = instId + DateUtil.formatDate(new Date(), "yyMM")
                + mchntBaseInfoBean.getIndustryType() + mchntNoSuffix;
        //初始化商户基本信息
        MchntBaseInfo mchntBaseInfo = InitParamUtil.initMchntBaseInfoByCreate(
                mchntBaseInfoBean, mchntContactsInfoBean, mchntNo,
                managerInfo, request);

        if (MchntTypeEnum.CHAIN_MCHNT_STORE.getMchntType().equals(mchntBaseInfoBean.getMchntType())) {
            //门店 查询是否有连锁门店信息
            MchntBaseInfoMapper mchntBaseInfoMapper = new MchntBaseInfoMapperImpl();
            MchntBaseInfo chainMchntInfo = mchntBaseInfoMapper.selectMchntBaseInfoByPrimaryKey(instId, mchntBaseInfoBean.getChainMchntNo());
            if (null == chainMchntInfo) {
                rglog.error("查询连锁商户信息为空！商户基本信息管理-新增门店商户失败！instId:{},ChainMchntNo:{}."
                        , instId, mchntBaseInfoBean.getChainMchntNo());
                throw new BizException(RespCodeEnum.CHAIN_IS_NULL.getRespCode(), RespCodeEnum.CHAIN_IS_NULL.getRespDesc());
            }

            if (BompAppParamConstant.FLAG_N.equals(mchntBaseInfo.getIndependentDataFlag())) {
                mchntBaseInfo.setMchntSettleMode(chainMchntInfo.getMchntSettleMode());
                mchntBaseInfo.setCashWithdrawalFlag(chainMchntInfo.getCashWithdrawalFlag());
                mchntBaseInfo.setMchntSettleMode(chainMchntInfo.getMchntSettleMode());
                mchntBaseInfo.setNoPasswordFlag(chainMchntInfo.getNoPasswordFlag());
            }
        }


        BizTmp bizTmp = new BizTmp();
        ConvertUtil.convertOutput(bizTmp);
        BeanUtil.beanCopy(mchntBaseInfo, bizTmp);
        bizTmp.setManageInstId(mchntBaseInfo.getSignInstId());
        bizTmp.setRealId(mchntBaseInfo.getId());
        bizTmp.setOprTableEname(TableNameConstant.T_B_MCHNT_BASE_INFO);
        //状态非正式
        bizTmp.setBizStatus(BizTmpStatusEnum.NO_NORMAL.getType());
        //新增
        bizTmp.setBizOpr("I");
        bizTmp.setAuditStatus(AuditStatusEnum.BE_AUDIT.getAuditStatus());
        //商户信息为主记录
        bizTmp.setDetailFlag(BompAppParamConstant.FLAG_N);
        bizTmp.setMasterShowFlag(request.getMasterShowFlag());
        String mchntBaseInfoJsonString = JSONObject.toJSONString(mchntBaseInfo);
        InitParamUtil.initBizTempData(bizTmp, mchntBaseInfoJsonString);
        //商户信息插入数据库
        createMchntBaseInfoData(xmlTreeUtil, mchntBaseInfo, bizTmp, null, mchntApexInfoBeanList);
        return mchntNo;
    }

    /**
     * 新增商户基础信息
     */
    private void createMchntBaseInfoData(XmlTreeUtil xmlTreeUtil,
                                         MchntBaseInfo mchntBaseInfo,
                                         BizTmp bizTmp,
                                         BizHistory bizHistory,
                                         List<MchntApexInfoBean> mchntApexInfoBeanList) throws Exception {
        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE,
                AppConfigConstant.MCMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MCMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        try {
            MchntBaseInfoMapper mchntBaseInfoMapper = new MchntBaseInfoMapperImpl();
            int dbResult = mchntBaseInfoMapper.insertMchntBaseInfo(mchntBaseInfo);
            if (dbResult != 0) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("新增商户基本信息表失败！");
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(),
                        RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }

            if (null != bizTmp) {
                BizTmpMapper bizTmpMapper = new BizTmpMapperImpl();
                dbResult = bizTmpMapper.insertBizTmp(bizTmp);
                if (dbResult != 0) {
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("新增商户基本信息-业务临时表记录失败！");
                    throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(),
                            RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                }
            }

            if (null != bizHistory) {
                BizHistoryMapper bizHistoryMapper = new BizHistoryMapperImpl();
                dbResult = bizHistoryMapper.insertBompBizHistory(bizHistory);
                if (dbResult != 0) {
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("新增商户基本信息-业务历史表记录失败！");
                    throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(),
                            RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                }
            }

            //商户扩展属性信息入库
            if (null != mchntApexInfoBeanList && !mchntApexInfoBeanList.isEmpty()) {
                MchntApexInfoMapper mchntApexInfoMapper = new MchntApexInfoMapperImpl();
                for (MchntApexInfoBean mchntApexInfoBean : mchntApexInfoBeanList) {
                    MchntApexInfo mchntApexInfo = new MchntApexInfo();
                    BeanUtil.beanCopy(mchntApexInfoBean, mchntApexInfo);
                    if (StringUtil.isEmptyOrNull(mchntApexInfo.getEffectiveDate())) {
                        mchntApexInfo.setEffectiveDate(DateUtil.getCurrentDate());
                    }
                    if (StringUtil.isEmptyOrNull(mchntApexInfo.getExpiryDate())) {
                        mchntApexInfo.setExpiryDate(BompAppParamConstant.DEFAULT_EXPIRY_DATE);
                    }
                    if (StringUtil.isEmptyOrNull(mchntApexInfo.getPropertyStatus())) {
                        mchntApexInfo.setPropertyStatus(AppParamConstant.YES);
                    }
                    mchntApexInfo.setInstId(mchntBaseInfo.getInstId());
                    mchntApexInfo.setMchntNo(mchntBaseInfo.getMchntNo());
                    mchntApexInfo.setId(RandomUtil.getUUID());
                    mchntApexInfo.setOprId(mchntBaseInfo.getOprId());
                    mchntApexInfo.setCreateTime(mchntBaseInfo.getCreateTime());
                    dbResult = mchntApexInfoMapper.insertMchntApexInfo(mchntApexInfo);
                    if (dbResult != 0) {
                        dbsUtil.dbsEndTransaction(false);
                        rglog.error("新增商户扩展属性信息记录失败！");
                        throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(),
                                RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                    }
                }
            }

            dbsUtil.dbsEndTransaction(true);
        } catch (Exception e) {
            dbsUtil.dbsEndTransaction(false);
            rglog.error("商户基本信息管理失败！mchntNo:{}", mchntBaseInfo.getMchntNo());
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        MchntBaseInfoManageResponse mchntBaseInfoManageResponse = (MchntBaseInfoManageResponse) bizResponse.getResult();
        ConvertUtil.convertInput(mchntBaseInfoManageResponse);
    }
}
